package com.yoj.judgeservice.service.impl;

import cn.hutool.json.JSONUtil;
import com.yoj.judgeservice.codesandbox.CodeSandbox;
import com.yoj.judgeservice.codesandbox.CodeSandboxProxy;
import com.yoj.judgeservice.strategy.JudgeContext;
import com.yoj.common.common.ResultCodeEnum;
import com.yoj.common.exception.BusinessException;
import com.yoj.judgeservice.codesandbox.CodeSandboxFactory;
import com.yoj.judgeservice.service.JudgeService;
import com.yoj.judgeservice.strategy.JudgeManager;
import com.yoj.model.codesandbox.ExecuteCodeRequest;
import com.yoj.model.codesandbox.ExecuteCodeResponse;
import com.yoj.model.codesandbox.JudgeInfo;
import com.yoj.model.dto.question.JudgeCase;
import com.yoj.model.entity.Question;
import com.yoj.model.entity.QuestionSubmit;
import com.yoj.model.enums.QuestionSubmitStatusEnum;
import com.yoj.serviceclient.service.question.QuestionFeignClient;
import com.yoj.serviceclient.service.sandbox.SandboxFeignClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 判题服务实现类
 */
@Service
@Slf4j
public class JudgeServiceImpl implements JudgeService {

    @Resource
    private QuestionFeignClient questionFeignClient;

    @Resource
    private SandboxFeignClient sandboxFeignClient;

    @Resource
    private JudgeManager judgeManager;

    @Resource
    private CodeSandboxFactory codeSandboxFactory;

    /**
     * 检验题目提交信息是否合法
     */
    public void validateDoJudge(long questionSubmitId) {
        // 1）传入题目的提交 id，获取到对应的题目、提交信息（包含代码、编程语言等)
        // 查询题目提交信息
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        if (questionSubmit == null) {
            throw new BusinessException(ResultCodeEnum.NOT_FOUND_ERROR, "提交信息不存在");
        }
        Long questionId = questionSubmit.getQuestionId();
        // 查询题目信息
        Question question = questionFeignClient.getQuestionById(questionId);
        if (question == null) {
            throw new BusinessException(ResultCodeEnum.NOT_FOUND_ERROR, "题目不存在");
        }
        // 2）如果题目提交状态不为等待中，就不用重复执行了
        if (!questionSubmit.getStatus().equals(QuestionSubmitStatusEnum.WAITTING.getValue())) {
            throw new BusinessException(ResultCodeEnum.OPERATION_ERROR, "题目正在判题中");
        }

    }

    /**
     * 远程调用代码沙箱，获取执行结果
     */
    public ExecuteCodeResponse executeCodeSandbox(QuestionSubmit questionSubmit) {
        Question question = questionFeignClient.getQuestionById(questionSubmit.getQuestionId());
        // 4）调用沙箱，获取到执行结果
        // 获取测试用例（json字符串->list）
        List<JudgeCase> judgeCaseList = JSONUtil.toList(question.getJudgeCase(), JudgeCase.class);
        // 从测试用例中获取输入用例
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());

        // 构建代码沙箱请求参数
        ExecuteCodeRequest executeCodeRequest = ExecuteCodeRequest.builder()
                .code(questionSubmit.getCode())
                .language(questionSubmit.getLanguage())
                .inputList(inputList)
                .build();

        // 调用代码沙箱服务，可传入不同的沙箱类型，默认是 remote
        CodeSandbox codeSandbox = codeSandboxFactory.newInstance();
        // 沙箱代理类，增强功能
        codeSandbox = new CodeSandboxProxy(codeSandbox);
        ExecuteCodeResponse executeCodeResponse = codeSandbox.executeCode(executeCodeRequest); // http 调用
        // ExecuteCodeResponse executeCodeResponse = sandboxFeignClient.executeCode(executeCodeRequest); // rpc 调用
        log.info("调用远程代码沙箱服务，执行结果：{}  ", executeCodeResponse.toString());
        return executeCodeResponse;
    }

    /**
     * 根据代码沙箱执行结果进行判题
     */
    public void judgeSubmitQuestion(QuestionSubmit questionSubmit, ExecuteCodeResponse executeCodeResponse) {
        Question question = questionFeignClient.getQuestionById(questionSubmit.getQuestionId());
        // 获取测试用例（json字符串->list）
        List<JudgeCase> judgeCaseList = JSONUtil.toList(question.getJudgeCase(), JudgeCase.class);
        // 从测试用例中获取输入用例
        List<String> inputList = judgeCaseList.stream().map(JudgeCase::getInput).collect(Collectors.toList());

        // 5）根据沙箱结果，判断代码是否有误，代码正常执行才进行判题
        // 从判题策略中获取沙箱执行结果
        // 封装上下文对象
        JudgeContext judgeContext = new JudgeContext()
                .setJudgeInfo(executeCodeResponse.getJudgeInfo())
                .setInputList(inputList)
                .setOutputList(executeCodeResponse.getOutputList())
                .setJudgeCaseList(judgeCaseList)
                .setQuestion(question)
                .setQuestionSubmit(questionSubmit);

        // 根据不同语言调用不同的判题策略
        JudgeInfo judgeInfo = judgeManager.doJudge(judgeContext);

        //6）修改数据库中的判题结果
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit()
                .setId(questionSubmit.getId())
                .setStatus(QuestionSubmitStatusEnum.SUCCESS.getValue())
                .setJudgeInfo(JSONUtil.toJsonStr(judgeInfo));
        boolean update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ResultCodeEnum.SYSTEM_ERROR, "题目状态更新错误");
        }

        // 判题通过，更新题目通过数
        synchronized (this) {
            Question updateQuestion = new Question()
                    .setId(questionSubmit.getQuestionId())
                    .setAcceptedNum(question.getAcceptedNum() + 1);
            boolean save = questionFeignClient.updateQuestionById(updateQuestion);
            if (!save) {
                throw new BusinessException(ResultCodeEnum.OPERATION_ERROR, "保存数据失败");
            }
        }
    }

    /**
     * 根据 questionSubmitId 进行判题
     */
    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public QuestionSubmit doJudge(long questionSubmitId) {
        validateDoJudge(questionSubmitId);

        // 3）更改判题（题目提交）的状态为 “判题中”，防止重复执行，也能让用户即时看到状态
        QuestionSubmit questionSubmitUpdate = new QuestionSubmit()
                .setId(questionSubmitId)
                .setStatus(QuestionSubmitStatusEnum.RUNNING.getValue());
        boolean update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
        if (!update) {
            throw new BusinessException(ResultCodeEnum.SYSTEM_ERROR, "题目状态更新错误");
        }

        // 获取题目和题目提交信息
        QuestionSubmit questionSubmit = questionFeignClient.getQuestionSubmitById(questionSubmitId);
        // 4）调用代码沙箱，获取到执行结果
        ExecuteCodeResponse executeCodeResponse = executeCodeSandbox(questionSubmit);

        // 代码沙箱执行错误无需继续进行判题，修改判题状态和判题信息后，直接返回
        if (executeCodeResponse.getStatus() != 1) {
            questionSubmitUpdate = new QuestionSubmit()
                    .setId(questionSubmitId)
                    .setStatus(QuestionSubmitStatusEnum.FAILED.getValue())
                    .setJudgeInfo(JSONUtil.toJsonStr(executeCodeResponse.getJudgeInfo()));
            // 根据题目提交 id 更新题目提交
            update = questionFeignClient.updateQuestionSubmitById(questionSubmitUpdate);
            if (!update) {
                throw new BusinessException(ResultCodeEnum.SYSTEM_ERROR, "题目状态更新错误");
            }
            return questionFeignClient.getQuestionSubmitById(questionSubmitId);
        }

        // 5）根据沙箱结果，判断代码是否有误，代码正常执行才进行判题
        judgeSubmitQuestion(questionSubmit, executeCodeResponse);

        // 获取题目最新状态
        return questionFeignClient.getQuestionSubmitById(questionSubmitId);
    }
}